import Head from '../../compontent/Header'
import style from './style.module.less'
import { Editor } from '@bytemd/react'
import gfm from '@bytemd/plugin-gfm'
import highlight from '@bytemd/plugin-highlight-ssr'
import math from '@bytemd/plugin-math'
import mermaid from '@bytemd/plugin-mermaid'
import mediumZoom from '@bytemd/plugin-medium-zoom'
import React, { ChangeEvent, useState } from 'react'
import * as api from '../../services/api'
import { Button, Form, Input, message } from 'antd'
import AddTags from '../../compontent/AddTags'
import UploadImg from '../../compontent/Upload'
import { useHistory } from 'react-router-dom'

export default function Create(props: any) {
  let token: string = props.match.params.id
  let limit: number = 20

  const [title, setTitle] = useState<string>('')
  const [md, setMD] = useState<string>('')
  const [banner, setBanner] = useState<string>('')
  const [tags, setTags] = useState<string[]>([])

  const history = useHistory()

  const plugins = [gfm(), math(), highlight(), mermaid(), mediumZoom()]

  function setTitleOnChang(e: ChangeEvent<HTMLInputElement>) {
    if (e.target.value.length <= limit) {
      setTitle(e.target.value)
    } else {
      setTitle(e.target.value.slice(0, limit))
      message.destroy()
      message.error(`标题长度不能超过${limit}个字符`)
    }
  }

  function setMdOnchange(md: string) {
    setMD(md)
  }

  async function uploadImg(files: File[]) {
    let url: string = ''
    const formDate = new FormData()
    formDate.append('file', files[0])
    let resUp = await api.uploadFile(token, formDate)
    if (resUp.data.stat === 'ok') {
      url = resUp.data.data.pathImg
    }
    const data: Pick<any, 'url'> = {
      url: `http://localhost:3000${url}`,
    }
    return [data]
  }

  async function addArticle() {
    try {
      let res = await api.addArticle(token, md, title, '', tags, [banner])
      if (res.data.stat === 'ok') {
        message.success('文章发布成功')
        history.push(`/personal/${token}`)
      } else {
        message.destroy()
        message.error(res.data.msg)
      }
    } catch (e) {
      throw e
    }
  }

  return (
    <>
      <Head token={token}>
        <title />
      </Head>
      <main className={style.main}>
        <Form.Item className={style.formItem}>
          标题:
          <Input
            value={title}
            onChange={(event) => setTitleOnChang(event)}
            className={style.formInput}
          />
          <Button
            type={'primary'}
            className={style.formButton}
            onClick={addArticle}>
            发布文章
          </Button>
        </Form.Item>
        <div className={style.formTagBanner}>
          <AddTags tags={''} getTags={(tag: string[]) => setTags(tag)} />
          <div className={style.formBanner}>
            <h3 style={{ width: '140px' }}>banner图: </h3>
            <UploadImg getImgKey={(imgKey: string) => setBanner(imgKey)} />
          </div>
        </div>
        <Editor
          value={md}
          plugins={plugins}
          onChange={(v: any) => setMdOnchange(v)}
          uploadImages={(files: File[]) => uploadImg(files)}
        />
      </main>
    </>
  )
}
